package com.gn.cc;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by GN on 2016/11/27.
 */
public class Template {

    private static final String TAG_PREFIX = "${";
    private static final String TAG_POSTFIX = "}";

    /**
     * 模板信息
     */
    private BufferedReader reader;
    private File file;
    /**
     * 模板标签,eg:${domain}：key=domain,value=${domain}
     */
    private Map<String, String> tag = new HashMap<>();

    public Template(File file) throws IOException {
        this.file = file;
        //初始化模板输入流
        initReader();
        //初始化模板标签
        //initFlag();
    }

    private void initReader() {
        if (file == null) {
            throw new IllegalArgumentException("获取模板失败");
        }
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file), "UTF-8");
            this.reader = new BufferedReader(inputStreamReader);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理标签到tag中
     *
     * @param text
     */
    private void initTag(String text) {
        if (!StringUtil.hasLength(text)) {
            return;
        }
        String tagFlag = getTagFlag(text);
        String tagText = getTagText(text);
        this.tag.put(tagText, tagFlag);
        //递归解析一行中的多个标签
        int prefix = text.indexOf(TAG_PREFIX);
        String subText = text.substring(prefix + 2 + tagText.length());
        if (hasTag(subText)) {
            initTag(subText);
        }
    }

    /**
     * 获取标签，${domain}
     *
     * @param text
     * @return
     */
    private String getTagFlag(String text) {
        int prefix = text.indexOf(TAG_PREFIX);
        int postfix = text.indexOf(TAG_POSTFIX);
        return text.substring(prefix, postfix + 1);
    }

    /**
     * 获取标签中的内容，${domain} --> domain
     *
     * @param text
     * @return
     */
    private String getTagText(String text) {
        String tagFlag = getTagFlag(text);
        return tagFlag.substring(2, tagFlag.length() - 1);
    }

    /**
     * 判断文本中是否含有标签
     *
     * @param text
     * @return
     */
    private boolean hasTag(String text) {
        if (!StringUtil.hasLength(text)) {
            return Boolean.FALSE;
        }
        return text.indexOf(TAG_PREFIX) > 0 && text.indexOf(TAG_POSTFIX) > 0;
    }

    /**
     * 生成模板
     *
     * @param context 模板值定义
     * @param target  目标生成文件
     */
    public void merge(GnContext context, File target) throws IOException {
        if (reader == null) {
            throw new IllegalArgumentException("读取模板失败");
        }
        //重置指针
        reader.mark(0);
        if (context == null) {
            throw new IllegalArgumentException("获取GnContext失败");
        }
        if (target == null) {
            throw new IllegalArgumentException("获取输出流失败");
        }
        String temp;
        FileWriter writer = new FileWriter(target, true);
        while ((temp = reader.readLine()) != null) {
            if (hasTag(temp)) {
                //解析出所有的标签
                List<String> tagTextList = findTagTextList(temp);
                if (!tagTextList.isEmpty()) {
                    for (String text : tagTextList) {
                        String value = context.get(text);
                        if (StringUtil.hasLength(value)){
                            temp = temp.replace(TAG_PREFIX + text + TAG_POSTFIX, value);
                        }
                    }
                }
            }
            writer.write(temp + "\n");
            writer.flush();
        }
        writer.close();
    }

    /**
     * 获取文本中的标签
     *
     * @param lineText
     * @return
     */
    private List<String> findTagTextList(String lineText) {
        List<String> tagTextList = new ArrayList<>();
        if (StringUtil.hasLength(lineText) && hasTag(lineText)) {
            String tmp = lineText;
            while (hasTag(tmp)) {
                String tagText = findTagText(tmp);
                if (!tagTextList.contains(tagText)) {
                    tagTextList.add(tagText);
                }
                int begin = tmp.indexOf(tagText);
                tmp = tmp.substring(begin + tagText.length()+1);
            }
        }
        return tagTextList;
    }

    /**
     * 获取文本中的单个标签
     *
     * @param text
     * @return
     */
    private String findTagText(String text) {
        if (!StringUtil.hasLength(text)) {
            return null;
        }
        return getTagText(text);
    }

}
